package com.joysuccess.snmp.producer;

import com.alibaba.fastjson.JSONObject;
import com.joysuccess.common.utils.HelpUtils;
import com.joysuccess.common.utils.SpringUtil;
import com.joysuccess.queue.protocol.AbstractSnmpProtocol;
import com.joysuccess.snmp.manager.SnmpManager;
import com.joysuccess.snmp.service.SnmpClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author : zhangqing
 * @Description: 动环监控snmpget的方式获取数据
 * @date : 2020年06月10日 20:22
 */
public class DynamicMonitorSnmpGetProtocol extends AbstractSnmpProtocol {
    private final Logger LOGGER = LoggerFactory.getLogger(DynamicMonitorSnmpGetProtocol.class);
    private final String dynamicTopic="haode-dynamic-datas";
    /**
     * 通过Spring获取Spring的ApplicationContext，并从中获取SnmpClientService和Environment
     */
    private SnmpClientService snmpClientService = SpringUtil.getBean(SnmpClientService.class);
    /**
     * 通过Environment获取properties文件中的属性
     */
    private String snmpId = SpringUtil.getApplicationContext().getEnvironment().getProperty("snmp.datas.ip");
    private Integer snmpPort = Integer.parseInt(SpringUtil.getApplicationContext().getEnvironment().getProperty("snmp.datas.port"));

    @Override
    public void getDataToSend() {
        Map<String, Map<String,String>> equipPointsList = snmpClientService.getEquipPointsMap();
        if(HelpUtils.isNotEmpty(equipPointsList)){
            //keySet是设备编号，值是设备对应的采集点信息
            Set<String> assetListPoints = equipPointsList.keySet();
            for (String assetId: assetListPoints) {
                //获取采集点数据集合
                Map<String,String> oidLists = equipPointsList.get(assetId);
                Set<String> oidIds =  oidLists.keySet();
                try {
                    //获取采集点的值，获取的结果是oid:varies信息
                    Map<String,String> resultMap = SnmpManager.snmpGetListBySet(snmpId,snmpPort,oidIds);
                    //将map转换为JSONString便于数据发送到Kafka中
                    String oidsList = JSONObject.toJSONString(resultMap);
                    JSONObject equipOids = new JSONObject();
                    //发送到kafka数据的格式是：设备：{oid:varies,oid:varies}，也就是当前设备下的采集点信息
                    equipOids.put("assetId",assetId);
                    equipOids.put("oidList",oidsList);
                    producerStrategy.sendRecordToQueue(dynamicTopic,equipOids.toJSONString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            LOGGER.warn("SNMP 数据发送到 Kafka失败，因为还没有进行Redis的数据的初始化，继续循环，等待数据被初始化");
        }
    }
}
